<?php

defined('SYSPATH') or die('No direct script access.');

class Controller_Backend_Images extends Controller_Backend {

    public function action_index()
    {
        $images = ORM::factory('image')->find_all();

        if($this->request->method() == Request::POST)
        {
            $file_images = $_FILES['images']['tmp_name'];

            if ( ! empty($file_images[0]))
            {
                foreach ($file_images as $image)
                {
                    $filename = Model_Image::upload($image);

                    $im_db = ORM::factory('image');
                    $im_db->user_id = $this->user->id;
                    $im_db->name = $filename;
                    $im_db->save();
                }

                $this->request->redirect('backend');
            }
            else
            {
                $errors = array(__(Kohana::message('validation', 'img_not_empty')));
            }

        }

        $content = View::factory('backend/images/v_images_index')
            ->bind('errors', $errors)
            ->bind('images', $images);

        $this->template->title_page = __('Photos');
        $this->template->content = $content;
    }


    public function action_add_comment()
    {

        if ($this->request->is_ajax())
        {
            $data = $this->request->post();
            $image = ORM::factory('image', $data['pk']);

            $this->auto_render = FALSE;

            if( ! $image->loaded())
                $this->request->redirect('backend');

            $image->$data['name'] = $data['value'];
            if($image->save())
            {
                echo json_encode(array('success' => true));
            }
            else
            {
                echo json_encode(array('success' => false));
            }

        }
    }

    public function action_delete()
    {

        if ($this->request->is_ajax())
        {
            $data = $this->request->post();
            $image = ORM::factory('image', $data['pk']);

            $this->auto_render = FALSE;

            if( ! $image->loaded())
                $this->request->redirect('backend');

            @unlink(Model_Image::DIRECTORY_PATH.$image->name);
            @unlink(Model_Image::DIRECTORY_PATH.'small_'.$image->name);

            if($image->delete())
            {
                echo json_encode(array('success' => true));
            }
            else
            {
                echo json_encode(array('success' => false));
            }

        }
    }
    
}